ardiudiu.log("dds.html.js starts.");

function dds_whatsappshare(dds_type, dds_content) {
	ardiudiu.log("dds_whatsappshare [" + dds_type + "], [" + dds_content + "]");
	var send_type = dds_type
	if (dds_type.indexOf("link") == 0) {
		if (dds_type.indexOf("base64") > 0)
			dds_content = window.encoder.decodeBase64(dds_content);
		dds_type = "link";
	}
	window.plugins['dds-plugin'].send_whatsapp({
		type : dds_type,
		content : dds_content
	}, function() {
		ardiudiu.successMsgStub("whatsapp OK.");

	}, function() {
		ardiudiu.errorMsgStub('open whatsapp FAIL')
	});
}

function dds_pull_perform_action(d) {
	// open a page dialog to ask for action

}

function dds_getPullPageData() {
	var result_string = '{"userhash":"31323235393531394040404040617264697564697540676d61696c2e636f6d","items":[{"type":"link","action":"share","target":"whatsapp","pagetitle":"Public - Dropbox","content":"aHR0cHM6Ly93d3cuZHJvcGJveC5jb20vaG9tZS9QdWJsaWM=","datetime":"2012-03-16 14:49:20","extra":{"hash":"base64"}}]}';
	var result = JSON.parse(result_string);
	// also do some post processing here
	// result.items.forEach(function(elm, i, arr) {
	// if (elm.type == "link") {
	// if (elm.extra && elm.extra.hash == "base64") {
	// elm.content = enc.decodeBase64(elm.content);
	// }
	// }
	// });
	return result.items;
}

function dds_pageshow(evt) {

}

function dds_homecreate(evt) {
}

function dds_getDropboxStatus() {
	var dropbox_status = "";
	require("cordova/platform");
	var db = window.openDatabase("dds", "1.0", "dds DB", 1000000);
	db.transaction(function(tx) {
		tx.executeSql('CREATE TABLE IF NOT EXISTS dds_SETTING(name unique, value)');
		tx.executeSql('SELECT value FROM dds_SETTING WHERE name = "dropbox-status"', [], function(tx, results) {
			ardiudiu.log("results.rows.legnth :" + results.rows.length);
			if (results.rows.length > 0) {
				dropbox_status = results.rows.item(0).value;
			}
		}, ardiudiu.errorMsgStub("DB select FAIL: "));
	}, ardiudiu.errorMsgStub("DB create FAIL"), ardiudiu.successMsgStub("DB create OK"));
	return dropbox_status;
}

function dds_homeinit(init_evt) {
	// open the database, and create necessary tables, if no setting found move
	// to setting page
	var dropboxstatus = dds_getDropboxStatus();
	if (dropboxstatus == "")
		dds_moveToPage("dds-setting");
}

function dds_refreshsettingpage(dropbox_status) {
	if (dropbox_status == "authorized") {
		$("#dds-setting").find('div[dds-id="not-authorized"]').hide();
		$("#dds-setting").find('div[dds-id="authorized"]').show();
	} else {
		$("#dds-setting").find('div[dds-id="not-authorized"]').show();
		$("#dds-setting").find('div[dds-id="authorized"]').hide();
	}
}

function dds_settinginit(init_evt) {
	var dropbox_status = dds_getDropboxStatus();
	dds_refreshsettingpage(dropbox_status);
}

function dds_settingshow(show_evt) {
//	var dropbox_status = dds_getDropboxStatus();
//	ardiudiu.log("dropbox_status = [" + dropbox_status + "]");
//	if (dropbox_status == "authorized") {
//		$("#dds-setting").find('div[dds-id="not-authorized"]').hide();
//	} else {
		// authorize it now, using the plugin
//		window.plugins['dds-plugin'].do_authorization({}, function(success) {
//
//			var db = window.openDatabase("dds", "1.0", "dds DB", 1000000);
//			db.transaction(function(tx) {
//				tx.executeSql('INSERT INTO dds_SETTING VALUES ("dropbox-status", "authorized")', [], function(tx, results) {
//					ardiudiu.successMsgStub("results.rows.legnth :" + results.rows.length);
//				}, ardiudiu.errorMsgStub("DB select FAIL: "));
//			}, ardiudiu.errorMsgStub("DB operation FAIL"), ardiudiu.successMsgStub("DB operation OK"));
//
//			ardiudiu.successMsgStub("do_authorization()");
//		}, function(error) {
//			ardiudiu.successMsgStub("do_authorization FAIL");
//		});
//		$("#dds-setting").find('div[dds-id="authorized"]').hide();
//	}
//	$("#dds-setting").trigger("refresh");
}

function dds_pullshow(show_evt) {
	// assume dropbox authorized, get data directly from dropbox
	var links = ardiudiu.hookBeginEnd(dds_getPullPageData)();
	var ul = $("#dds-pull").find("ul");
	var li = ul.find('li[data-role="list-divider"]').detach();
	ul.empty();
	ul.append(li);
	links.forEach(function(link, i, arr) {
		var showtitle = "";
		var showtext = "";
		var datetime = "";
		var onclickopt = "";
		var onclickparam = {};
		if (link.type == "link") {
			showtitle = link.pagetitle;
			showtext = link.content;
			if (link.extra && link.extra.hash == "base64")
				showtext = window.encoder.decodeBase64(link.content);
			datetime = link.datetime;
		}
		if (link.target == "whatsapp")
			onclickopt = "dds_whatsappshare('" + link.type + "_" + "base64" + "', '" + link.content + "')";
		var itemstr = '<li data-icon="false"><a onclick="' + onclickopt + '"><h3>' + showtitle + '</h3>';
		if (showtext)
			itemstr += '<p>' + showtext + '</p>';
		if (datetime)
			itemstr += '<p align="right">' + datetime + '</p>';
		itemstr += '</a></li>';
		ul.append($(itemstr));
	});
	ul.listview("refresh");
}

$(document).on({
	"pagecreate" : ardiudiu.hookBeginEnd(dds_homecreate),
	"pageinit" : ardiudiu.hookBeginEnd(dds_homeinit)
}, "#home");

$(document).on({
	"pageshow" : ardiudiu.hookBeginEnd(dds_settingshow),
	"pageinit" : ardiudiu.hookBeginEnd(dds_settinginit),
}, "#dds-setting");

$(document).on({
	"pageshow" : ardiudiu.hookBeginEnd(dds_pullshow)
}, "#dds-pull");

$(document).on({
	"pageshow" : function(show_evt) {
		$('div[data-id="dds-navbar"]').find('a').each(function(i, elm) {
			if ($(this).attr("dds-href") == show_evt.currentTarget.id)
				$(this).addClass("ui-btn-active");
			else
				$(this).removeClass("ui-btn-active");
		});
	}
}, '#dds-pull,#dds-push,#dds-setting');

function dds_moveToPage(pageid) {
	$.mobile.changePage($("#" + pageid), {
		allowSamePageTransition : false,
		changeHash : false
	});
}